<?php

namespace Modules\Coupon\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Illuminate\Support\Facades\DB;
use Modules\Coupon\Entities\Coupon;
use \Modules\Product\Entities\Product;
use \Modules\Box\Entities\Box;

use Validator;
use ThrowException;
use Auth;
use Setting;

class CouponController extends Controller
{
    public function useableIndex(Request $req)
    {
        $rule = [
            'type' => ['required'],
            'total' => ['required'],
            'id' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $coupons = $user->coupons()->valid()->get();

        $type = $req->type == 'box' ? 0 : 1;

        $item = NULL;
        $item = $type == 0 ? Box::getEntity([
            'id' => $req->id
        ]) : Product::getEntity([
            'id' => $req->id
        ]);

        $res = [];
        foreach ($coupons as $coupon) {
            if ($coupon->base_coupon->usable_range_type == 2 || (is_array($coupon->base_coupon->usable_ids)
                && ($coupon->base_coupon->usable_range_type == $type
                && in_array($req->id, $coupon->base_coupon->usable_ids)))) {

                if ($coupon->base_coupon->minimum_money && ($item->price < $coupon->base_coupon->minimum_money))
                    continue;

                if ($item->price > $coupon->base_coupon->discount_money)
                    array_push($res, $coupon->getInfo([
                        'id',
                        'uuid',
                        'usable_start_at',
                        'usable_end_at',
                        'base_coupon' => [
                            'title',
                            'description',
                            'usable_range_type',
                            'money_limit_type',
                            'minimum_money',
                            'discount_type',
                            'discount_money',
                            'discount_rate',
                            'discount_money_limit',
                        ]
                    ]));
            }
        }

        return [
            'list' => $res
        ];
    }

    public function index(Request $req)
    {
        $rule = [
            'ids' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $options = $req->all();

        $options['scopes'] = ['available', 'onStock'];

        $options['only'] = [
            'id',
            'uuid',
            'title',
            'description',
            'money_limit_type',
            'minimum_money',
            'discount_type',
            'discount_money',
            'discount_rate',
            'discount_money_limit',
            'time_limit_type',
            'valid_time',
            'usable_range_type',
            'usable_start_at',
            'usable_end_at',
            'usable_range_text',
            'to_use_link',
            'usable_ids',
            'is_picked'
        ];

        $list = Coupon::getList($options);

        $list->each(function ($coupon) use ($user) {
            $coupon->is_picked = $coupon->isPickedBy($user) ? 1 : 0;
        });

        $res = $list->generateListResponse();

        foreach ( $res['list'] as $k => $v ){
            $res['list'][$k]['to_link_title'] = '';

            if ( @$v['to_use_link'] ){
                if ( @isset($v['to_use_link']['type']) ){
                    $usable_ids = isset($v['usable_ids'][0]) ? $v['usable_ids'][0] : 0;
                    if ( $v['to_use_link']['type'] == 'fudai' && $usable_ids ){
                        $act = DB::table('fudai_activity')->where('id', $usable_ids)->first();
                        $res['list'][$k]['to_link_title'] = $act->title;
                    }

                    if ( $v['to_use_link']['type'] == 'leitai' && $usable_ids ){
                        $act = DB::table('leitai_activity')->where('id', $usable_ids)->first();
                        $res['list'][$k]['to_link_title'] = $act->title;
                    }

                    if ( $v['to_use_link']['type'] == 'choushang' && $usable_ids ){
                        $act = DB::table('choushang_activity')->where('id', $usable_ids)->first();
                        $res['list'][$k]['to_link_title'] = $act->title;
                    }

                }
            }
        }

        return $res;
    }

    // 首页弹窗的优惠券列表
    public function popupIndex(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // $user = Auth::requireLoginUser();

        $options = $req->all();

        $options['scopes'] = ['available', 'onStock'];
        $options['per_page'] = 5;

        $options['ids'] = @Setting::get('sys_coupon_popup')['coupon_ids'] ?: [0];

        $options['only'] = [
            'id',
            'uuid',
            'title',
            'description',
            'money_limit_type',
            'minimum_money',
            'discount_type',
            'discount_money',
            'discount_rate',
            'discount_money_limit',
            'time_limit_type',
            'valid_time',
            'usable_range_type',
            'usable_start_at',
            'usable_end_at',
            'usable_range_text',
            'is_picked'
        ];

        $list = Coupon::getList($options);

        return $list->generateListResponse();
    }

    // 领取首页弹窗中的优惠券
    public function pickPopup(Request $req)
    {
        $user = Auth::requireLoginUser();

        $setting = @Setting::get('sys_coupon_popup') ?: [];

        if (@$setting['is_enabled'] && @$setting['coupon_ids']) {
            $list = Coupon::whereIn('id', $setting['coupon_ids'])->available()->onStock()->get();

            foreach ($list as $coupon) {
                $coupon->pushTo($user, 'manual', false);
            }
        }

        return [];
    }

    public function store(Request $req)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $info = $req->all();

        $item = Coupon::create($info);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function show(Request $req, $uuid)
    {
        $rule = [
            // 'address_id' => ['integer']
        ];

        $user = Auth::requireLoginUser();

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $info = $req->all();

        $item = Coupon::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        $info['is_picked'] = $item->isPickedBy(Auth::user());

        $info['to_link_new'] = '';
        $info['to_link_title'] = '';
        if ( $info['to_use_link'] ){
            if ( isset($info['to_use_link']['type']) ){
                $usable_ids = isset($info['usable_ids'][0]) ? $info['usable_ids'][0] : 0;
                if ( $info['to_use_link']['type'] == 'fudai' && $usable_ids ){
                    $act = DB::table('fudai_activity')->where('id', $usable_ids)->first();
                    $info['to_link_new'] = '/pages/fudai/detail?uuid='.$act->uuid;
                    $info['to_link_title'] = $act->title;
                }

                if ( $info['to_use_link']['type'] == 'leitai' && $usable_ids ){
                    $act = DB::table('leitai_activity')->where('id', $usable_ids)->first();
                    $info['to_link_new'] = '/packageA/pages/leiTai/index?title='.urlencode($act->title).'&imgUrl='.$act->thumb;
                    $info['to_link_title'] = $act->title;
                }

                if ( $info['to_use_link']['type'] == 'choushang' && $usable_ids ){
                    $act = DB::table('choushang_activity')->where('id', $usable_ids)->first();
                    $info['to_link_new'] = '/packageA/pages/chouShang/index?title='.urlencode($act->title).'&imgUrl='.$act->thumb;
                    $info['to_link_title'] = $act->title;
                }

            }
        }

        return [
            'info' => $info
        ];
    }
}
